package com.wx;


import db.persistence.WxuserinforMapper;

import db.pojo.Wxuserinfor;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import weixin.common.api.WxConsts;
import  weixin.common.bean.WxMenu;
import  weixin.common.bean.WxMenu.WxMenuButton;
import  weixin.common.bean.result.WxMediaUploadResult;
import  weixin.common.exception.WxErrorException;
import  weixin.common.util.StringUtils;
import  weixin.mp.api.*;
import  weixin.mp.api.WxMpMessageHandler;

asdf



asdf


import  weixin.mp.api.WxMpMessageRouter;
import  weixin.mp.api.WxMpService;
import  weixin.mp.bean.WxMpMpXmlOutImageMessage;
import  weixin.mp.bean.WxMpXmlMessage;
import  weixin.mp.bean.WxMpXmlOutMessage;
import  weixin.mp.bean.WxMpXmlOutTextMessage;
import  weixin.mp.bean.result.WxMpUser;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 
 * @author ThinkPad
 * 
 * 生成环境地址 http://112.126.73.95/weixin/IceAlliancewx
 * 
 */
public class WxMpServlet extends HttpServlet {

	protected String lang = "zh_CN";
	protected WxMpConfigStorage wxMpConfigStorage;
	protected WxMpService wxMpService;
	protected WxMpMessageRouter wxMpMessageRouter;

	protected String currentOpenid = "";



    @Override
	public void init() throws ServletException {
		super.init();
		System.out.println(" ====in   init   ==");
		// WxMpInMemoryConfigStorage config = new WxMpInMemoryConfigStorage();
		// config.setAppId("wx00ec8ee47e83ae10"); // 设置微信公众号的appid
		// config.setSecret("e70ba5546dbc07a06a85618da3d3a428"); // 设置微信公众号的app
		// corpSecret
		// // corpSecret
		// config.setToken("IceAlliancehansen"); // 设置微信公众号的token
		// config.setAesKey("VFRhR3UCz8L1M24iBremPI9G7Oxe9lWbFtFEv7SJnyd"); //
		// 设置微信公众号的EncodingAESKey

		// config.setAppId(IceAllianceConstant.APPID); // 设置微信公众号的appid
		// config.setSecret(IceAllianceConstant.SECRET); // 设置微信公众号的app corpSecret
		// config.setToken(IceAllianceConstant.TOKEN); // 设置微信公众号的token
		// config.setAesKey(IceAllianceConstant.AESKEY); // 设置微信公众号的EncodingAESKey
		//		
		// config.setOauth2redirectUri("http://112.126.73.95/weixin/openid.jsp");//====oauth
		// url
		//
		// wxMpService = new WxMpServiceImpl();
		// wxMpService.setWxMpConfigStorage(config);

		wxMpService = WxUtil.getInstance();
		// this.createMenu();// 创建自定义菜单

		WxMpMessageHandler handlerMenu = new WxMpMessageHandler() {
			@Override
			public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
					Map<String, Object> context, WxMpService wxMpService) {
				System.out.println(" ==in menuHandler ");
				WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT().content(
						IceAllianceConstant.TEXT_MENU).fromUser(
						wxMessage.getToUserName()).toUser(
						wxMessage.getFromUserName()).build();

				return m;
			}
		};

		WxMpMessageHandler handlerD1 = new WxMpMessageHandler() {
			@Override
			public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
					Map<String, Object> context, WxMpService wxMpService) {

				String href = " 请点击-> <a href=' " + IceAllianceConstant.MENU_ABOUT
						+ wxMessage.getFromUserName() + "'>  冰盟说明 </a>\n "
						+ IceAllianceConstant.TEXT_MENU;
				WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT()
						.content(href).fromUser(wxMessage.getToUserName())
						.toUser(wxMessage.getFromUserName()).build();

				return m;
			}
		};

		WxMpMessageHandler handlerD2 = new WxMpMessageHandler() {
			@Override
			public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
					Map<String, Object> context, WxMpService wxMpService) {
				String href = " 请点击-> <a href=' " + IceAllianceConstant.MENU_CLUBLIST
						+ wxMessage.getFromUserName() + "'> 场馆列表 </a>\n "
						+ IceAllianceConstant.TEXT_MENU;
				WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT()
						.content(href).fromUser(wxMessage.getToUserName())
						.toUser(wxMessage.getFromUserName()).build();

				return m;
			}
		};

		WxMpMessageHandler handlerD3 = new WxMpMessageHandler() {
			@Override
			public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
					Map<String, Object> context, WxMpService wxMpService) {
				String href = "请点击-> <a href=' " + IceAllianceConstant.MENU_MYIceAlliance
						+ wxMessage.getFromUserName() + "'>  我的冰盟 </a>\n "
						+ IceAllianceConstant.TEXT_MENU;
				WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT()
						.content(href).fromUser(wxMessage.getToUserName())
						.toUser(wxMessage.getFromUserName()).build();

				return m;
			}
		};

		WxMpMessageHandler handlerWelcome = new WxMpMessageHandler() {
			@Override
			public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
					Map<String, Object> context, WxMpService wxMpService) {

				createMenu(wxMessage.getFromUserName());// 关注的时候 发菜单

                System.out.println(wxMessage.getFromUserName());
                System.out.println("guanzhu");
                String username = "";
				try {

					WxMpUser user = wxMpService.userInfo(wxMessage
							.getFromUserName(), lang);// 获取微信用户信息
                    username=user.getNickname();
                    System.out.println("获取微信用户信息");
                    System.out.println(user.toString());

                    ApplicationContext appContext = new ClassPathXmlApplicationContext("/applicationContext.xml");
                    WxuserinforMapper mapper = appContext.getBean(WxuserinforMapper.class);

                    Wxuserinfor wxuserinfor = new Wxuserinfor();
                    wxuserinfor.setNickname(user.getNickname());
                    wxuserinfor.setImgurl(user.getHeadImgUrl());
                    wxuserinfor.setOpenid(user.getOpenId());
                    wxuserinfor.setUnoinid(user.getUnionId());
                    mapper.insert(wxuserinfor);
                    System.out.println("微信关注用户信息插入数据库");
                    System.out.println( wxuserinfor.toString());



				} catch (WxErrorException e) {
					// TODO Auto-generated catch block
                    System.out.println("guanzhu出错");
					e.printStackTrace();
				}

				WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT().content(
                        username+"  "+IceAllianceConstant.TEXT_WELCOME).fromUser(
						wxMessage.getToUserName()).toUser(
						wxMessage.getFromUserName()).build();
                System.out.println("发送欢迎信息");

				return m;
			}
		};

		// ======
		WxMpMessageHandler handlerPos = new WxMpMessageHandler() {
			@Override
			public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
					Map<String, Object> context, WxMpService wxMpService) {

				try {

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				return null;
			}
		};

		// ====图片消息
		WxMpMessageHandler imageHandler = new WxMpMessageHandler() {
			@Override
			public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
					Map<String, Object> context, WxMpService wxMpService) {
			/*	try {
					WxMediaUploadResult wxMediaUploadResult = wxMpService
							.mediaUpload(
									WxConsts.MEDIA_IMAGE,
									WxConsts.FILE_JPG,
									ClassLoader
											.getSystemResourceAsStream("dbsm.jpg"));
					WxMpMpXmlOutImageMessage m = WxMpXmlOutMessage.IMAGE()
							.mediaId(wxMediaUploadResult.getMediaId())
							.fromUser(wxMessage.getToUserName()).toUser(
									wxMessage.getFromUserName()).build();
					return m;
				} catch (WxErrorException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}*/
/*            Logger logger= (Logger) LoggerFactory.getLogger(WxMpServlet.class);
logger.info();*/

                    String imgreply = "发张图片给我干什么？"
                            ;
                    WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT()
                            .content(imgreply).fromUser(wxMessage.getToUserName())
                            .toUser(wxMessage.getFromUserName()).build();

                    return m;

			}
		};

		// ===授权消息
		// WxMpMessageHandler oauth2handler = new WxMpMessageHandler() {
		// @Override
		// public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
		// Map<String, Object> context, WxMpService wxMpService) {
		// String href = "<a href=\""
		// + wxMpService.oauth2buildAuthorizationUrl(
		// WxConsts.OAUTH2_SCOPE_USER_INFO, null)
		// + "\">测试oauth2</a>";
		// return WxMpXmlOutMessage.TEXT().content(href).fromUser(
		// wxMessage.getToUserName()).toUser(
		// wxMessage.getFromUserName()).build();
		// }
		// };

		WxMpMessageHandler oauth2handler = new WxMpMessageHandler() {
			@Override
			public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
					Map<String, Object> context, WxMpService wxMpService) {
				String href = "<a href=\""
						+ wxMpService.oauth2buildAuthorizationUrl(
								WxConsts.OAUTH2_SCOPE_USER_INFO, "myIceAlliance")
						+ "\">测试oauth2</a>";
				return WxMpXmlOutMessage.TEXT().content(href).fromUser(
						wxMessage.getToUserName()).toUser(
						wxMessage.getFromUserName()).build();
			}
		};

		wxMpMessageRouter = new WxMpMessageRouter(wxMpService);
		wxMpMessageRouter.rule().async(false).event(WxConsts.EVT_SUBSCRIBE)
				.handler(handlerWelcome).end();// 关注事件
		wxMpMessageRouter.rule().async(false).event(WxConsts.EVT_LOCATION)
				.handler(handlerPos).end();// 定位
		wxMpMessageRouter.rule().async(false).msgType(WxConsts.XML_MSG_TEXT)
				.content("1").handler(handlerD1).end();
		wxMpMessageRouter.rule().async(false).msgType(WxConsts.XML_MSG_TEXT)
				.content("2").handler(handlerD2).end();
		wxMpMessageRouter.rule().async(false).msgType(WxConsts.XML_MSG_TEXT)
				.content("3").handler(handlerD3).end();
		wxMpMessageRouter.rule().async(false).msgType(WxConsts.XML_MSG_TEXT)
				.content("test").handler(oauth2handler).end();
		wxMpMessageRouter.rule().async(false).msgType(WxConsts.XML_MSG_TEXT)
				.rContent(".*").handler(handlerMenu).end();

        wxMpMessageRouter.rule().async(false).msgType(WxConsts.XML_MSG_IMAGE)
               .handler(imageHandler).end();

	}

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		response.setStatus(HttpServletResponse.SC_OK);

		String signature = request.getParameter("signature");
		String nonce = request.getParameter("nonce");
		String timestamp = request.getParameter("timestamp");

		Map<String, String[]> map = request.getParameterMap();
		for (String key : map.keySet()) {
			String[] values = (String[]) map.get(key);
			System.out.println("Key = " + key + "  value:"
					+ request.getParameter(key));
		}

		if (!wxMpService.checkSignature(timestamp, nonce, signature)) {

			response.getWriter().println("非法请求");
			System.out.println(" ======3 非法请求==");
			return;
		}

		String echostr = request.getParameter("echostr");
		if (StringUtils.isNotBlank(echostr)) {
			// 说明是一个仅仅用来验证的请求，回显echostr
			System.out.println(" =======4 " + echostr);
			response.getWriter().println(echostr);
			return;
		}

		String encryptType = StringUtils.isBlank(request
				.getParameter("encrypt_type")) ? "raw" : request
				.getParameter("encrypt_type");

		if ("raw".equals(encryptType)) {
			// 明文传输的消息
			WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(request
					.getInputStream());
			currentOpenid = inMessage.getFromUserName();

			WxMpXmlOutMessage outMessage = wxMpMessageRouter.route(inMessage);
			if (outMessage != null) {
				System.out
						.println(" ==response message: " + outMessage.toXml());
				response.getWriter().write(outMessage.toXml());
			}

			return;
		}

		if ("aes".equals(encryptType)) {
			// 是aes加密的消息
			String msgSignature = request.getParameter("msg_signature");
			WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(request
					.getInputStream(), wxMpConfigStorage, timestamp, nonce,
					msgSignature);
			WxMpXmlOutMessage outMessage = wxMpMessageRouter.route(inMessage);
			response.getWriter().write(
					outMessage.toEncryptedXml(wxMpConfigStorage));
			return;
		}

		response.getWriter().println("不可识别的加密类型");
		return;
	}

	private void createMenu(String openid) {
        System.out.println("menuinit");
         /*     openid = "";*/
		WxMenu wxMenu = new WxMenu();
		WxMenuButton bt1 = new WxMenuButton();
		WxMenuButton bt2 = new WxMenuButton();
		WxMenuButton bt3 = new WxMenuButton();
		bt1.setName("前台");
		WxMenuButton bt1_about = new WxMenuButton();
		bt1_about.setName("订场");
		bt1_about.setType(WxConsts.BUTTON_VIEW);
		bt1_about.setUrl(IceAllianceConstant.MENU_ABOUT);

		bt1.getSubButtons().add(bt1_about);

		WxMenuButton bt1_Buyticket= new WxMenuButton();
        bt1_Buyticket.setName("买票");
        bt1_Buyticket.setType(WxConsts.BUTTON_VIEW);
/*        wxMpConfigStorage.getOauth2redirectUri();*/
        System.out.println("test");
        String url = wxMpService.oauth2buildAuthorizationUrl(
				WxConsts.OAUTH2_SCOPE_BASE, "myIceAlliance");
	 System.out.println(" ===oauth2==url=:"+url);
        bt1_Buyticket.setUrl(url);
		bt1.getSubButtons().add(bt1_Buyticket);

        WxMenuButton bt1_Recharge = new WxMenuButton();
        bt1_Recharge.setName("充值");
        bt1_Recharge.setType(WxConsts.BUTTON_VIEW);
/*        wxMpConfigStorage.getOauth2redirectUri();*/

        String url2 = wxMpService.oauth2buildAuthorizationUrl(
                WxConsts.OAUTH2_SCOPE_BASE, "myIceAlliance");
        System.out.println(" ===oauth2==url=:"+url2);
        bt1_Recharge.setUrl(url2);
        bt1.getSubButtons().add(bt1_Recharge);

        WxMenuButton bt1_Buycard= new WxMenuButton();
        bt1_Buycard.setName("买卡");
        bt1_Buycard.setType(WxConsts.BUTTON_VIEW);
/*        wxMpConfigStorage.getOauth2redirectUri();*/

        String url3 = wxMpService.oauth2buildAuthorizationUrl(
                WxConsts.OAUTH2_SCOPE_BASE, "myIceAlliance");
        System.out.println(" ===oauth2==url=:"+url3);
        bt1_Buycard.setUrl(url3);
        bt1.getSubButtons().add(bt1_Buycard);

        WxMenuButton bt1_Shopping= new WxMenuButton();
        bt1_Shopping.setName("买商品");
        bt1_Shopping.setType(WxConsts.BUTTON_VIEW);
/*        wxMpConfigStorage.getOauth2redirectUri();*/

        String url4 = wxMpService.oauth2buildAuthorizationUrl(
                WxConsts.OAUTH2_SCOPE_BASE, "myIceAlliance");
        System.out.println(" ===oauth2==url=:"+url4);
        bt1_Shopping.setUrl(url4);
        bt1.getSubButtons().add(bt1_Shopping);

		bt2.setName("消息");
		WxMenuButton bt2_breaks = new WxMenuButton();
        bt2_breaks.setName("优惠");
        bt2_breaks.setType(WxConsts.BUTTON_VIEW);
		String club_url = wxMpService.oauth2buildAuthorizationUrl(
				WxConsts.OAUTH2_SCOPE_BASE, "club");
        bt2_breaks.setUrl(club_url);
		bt2.getSubButtons().add(bt2_breaks);

		WxMenuButton bt2_active = new WxMenuButton();
        bt2_active.setName("活动");
        bt2_active.setType(WxConsts.BUTTON_VIEW);
		String space_url = wxMpService.oauth2buildAuthorizationUrl(
				WxConsts.OAUTH2_SCOPE_BASE, "space");
        bt2_active.setUrl(space_url);
		bt2.getSubButtons().add(bt2_active);

		WxMenuButton bt2_Match = new WxMenuButton();
        bt2_Match.setName("赛事");
        bt2_Match.setType(WxConsts.BUTTON_VIEW);
		String clublist_url = wxMpService.oauth2buildAuthorizationUrl(
				WxConsts.OAUTH2_SCOPE_BASE, "clublist");
        bt2_Match.setUrl(clublist_url);
		bt2.getSubButtons().add(bt2_Match);

		bt3.setName("我的");

		WxMenuButton bt3_dongba = new WxMenuButton();
		bt3_dongba.setName("订单");
		bt3_dongba.setType(WxConsts.BUTTON_VIEW);
		String myIceAlliance_url = wxMpService.oauth2buildAuthorizationUrl(
				WxConsts.OAUTH2_SCOPE_BASE, "myIceAlliance");
		bt3_dongba.setUrl(myIceAlliance_url);
		bt3.getSubButtons().add(bt3_dongba);

		WxMenuButton bt3_orders = new WxMenuButton();
		bt3_orders.setName("会员卡");
		bt3_orders.setType(WxConsts.BUTTON_VIEW);
		String myorder_url = wxMpService.oauth2buildAuthorizationUrl(
				WxConsts.OAUTH2_SCOPE_BASE, "myorder");
		bt3_orders.setUrl(myorder_url);
		bt3.getSubButtons().add(bt3_orders);

        WxMenuButton bt3_Records = new WxMenuButton();
        bt3_Records.setName("消费记录");
        bt3_Records.setType(WxConsts.BUTTON_VIEW);
        String Records_url = wxMpService.oauth2buildAuthorizationUrl(
                WxConsts.OAUTH2_SCOPE_BASE, "myorder");
        bt3_Records.setUrl(Records_url);
        bt3.getSubButtons().add(bt3_Records);



		wxMenu.getButtons().add(bt1);
		wxMenu.getButtons().add(bt2);
		wxMenu.getButtons().add(bt3);

		try {
			System.out.println(" =====in  menuCreate=====");
			wxMpService.menuCreate(wxMenu);

		} catch (WxErrorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

/*        wxMenu.setButtons(wxMenu);*/
    }
}
